package util;

import java.util.Hashtable;
import java.util.Vector;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.gson.Gson;

public class ServerToClient {
	
	public static final int NEW_MESSAGE = 1;
	public static final int NEW_USER_JOIN = 2;
	public static final int NEW_BOARD_PATH = 3;
	
	static String getChannelKey(String sUsername)
	{
		return "channelchat_" + sUsername;
	}
	
	public static void sendMessageToAllUsers(int iCode, Object oData, String sEmail)
	{
		Hashtable hObjectReturn = new Hashtable();
		hObjectReturn.put("code", iCode);
		hObjectReturn.put("data", oData);
		if(sEmail.compareTo("") != 0)
			hObjectReturn.put("email", sEmail);
		Gson gson = new Gson();        
		String sMessage = gson.toJson(hObjectReturn);
		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		Vector<String> vUsers = (Vector<String>) syncCache.get("room1");
		if(vUsers.size() > 0)
		{
			for(String sUsername : vUsers)
			{
				ChannelService channelService = ChannelServiceFactory.getChannelService();
				channelService.sendMessage(new ChannelMessage(getChannelKey(sUsername), sMessage));
			}
		}
	}
}
